package cn.kk.pzhu.gpaweb.service.impl;

import cn.kk.pzhu.gpaweb.dao.StudentMapper;
import cn.kk.pzhu.gpaweb.entity.Student;
import cn.kk.pzhu.gpaweb.entity.UserVO;
import cn.kk.pzhu.gpaweb.utils.CrawlerUtils;
import cn.kk.pzhu.gpaweb.utils.HttpClientConfig;
import org.apache.commons.httpclient.NameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author KK
 * @CreateTime 2022-08-29
 */
@Service
public class MainServiceImpl {

    @Autowired
    private StudentMapper studentMapper;

    public String login(String userAccount, String userPassword, String loginMethod, String encoded) {
        // 1
        String loginUrl = "http://jwci.pzhu.cn/jsxsd/xk/LoginToXk";
        //登录才能进入
        String dataUrl = "http://jwci.pzhu.cn/jsxsd/framework/xsMain.jsp";
        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] loginInfo = {new NameValuePair("userAccount", userAccount),
                new NameValuePair("userPassword", userPassword),
                new NameValuePair("loginMethod", loginMethod),
                new NameValuePair("encoded", encoded)};
        try {
            String cookie = CrawlerUtils.post(loginUrl, loginInfo);
            Map<String, String> map = new HashMap<>();
            map.put("Cookie", cookie);
//            String html = CrawlerUtils.get(dataUrl, map);

            return cookie;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "false";
    }

    public UserVO getInfo(String cookie) throws SQLException {
        return getInfoStudent(cookie, "http://jwci.pzhu.cn/jsxsd/grxx/xsxx");
    }

    public UserVO getInfoStudent(String cookie, String url) throws SQLException {
        UserVO student = new UserVO();
        //获取用户基本信息 学院、专业、年级、班级、姓名、电话、生日、政治面貌
        //学院 #xjkpTable > tbody > tr:nth-child(3) > td:nth-child(1)  院系：数学与计算机学院(大数据学院)    拆分 ：
        //专业 #xjkpTable > tbody > tr:nth-child(3) > td:nth-child(2)  专业：软件工程                     拆分 ：
        //年级 #xjkpTable > tbody > tr:nth-child(3) > td:nth-child(4)  班级：2020级软件工程本科1班         拆分 ： 【1】级【0】
        //班级 #xjkpTable > tbody > tr:nth-child(3) > td:nth-child(4)  班级：2020级软件工程本科1班         拆分 ： 【1】级【1】  然后获取里面的数字，若没有数字则为0班
        //姓名 #xjkpTable > tbody > tr:nth-child(4) > td:nth-child(2)  xxx         需要去除空格
        //电话 #xjkpTable > tbody > tr:nth-child(5) > td:nth-child(6)  xxxxxxxxxx  需要去除空格
        //生日 #xjkpTable > tbody > tr:nth-child(5) > td:nth-child(2)  20010821    需要去除空格且转换为date类型
        //政治 #xjkpTable > tbody > tr:nth-child(6) > td:nth-child(4)  xxxx        需要去除空格
        //性别 #xjkpTable > tbody > tr:nth-child(4) > td:nth-child(4)  男          需要去除空格
//        String cookie = login(userAccount, userPassword, "LoginToXk", encoded);
        //表单网页
        Document user = Jsoup.parse(HttpClientConfig.doGetInfo(cookie, url));
        Element is = user.selectFirst("#xjkpTable > tbody > tr:nth-child(3) > td:nth-child(1)");
        if (Objects.isNull(is)) {
            return null;
        }
        //学院
        String college = user.selectFirst("#xjkpTable > tbody > tr:nth-child(3) > td:nth-child(1)").text().split("：")[1];
        //专业
        String major = user.selectFirst("#xjkpTable > tbody > tr:nth-child(3) > td:nth-child(2)").text().split("：")[1];
        //年级
        String classes = user.selectFirst("#xjkpTable > tbody > tr:nth-child(3) > td:nth-child(4)").text().split("：")[1].split("级")[0];
        //班级
        String grade = getClasses(user.selectFirst("#xjkpTable > tbody > tr:nth-child(3) > td:nth-child(4)").text().split("：")[1].split("级")[1]);
        //性别
        String sex = user.selectFirst("#xjkpTable > tbody > tr:nth-child(4) > td:nth-child(4)").text().replaceAll("\\s*", "");
        //姓名
        String name = user.selectFirst("#xjkpTable > tbody > tr:nth-child(4) > td:nth-child(2)").text().replaceAll("\\s*", "");
        //电话
        String mobile = user.selectFirst("#xjkpTable > tbody > tr:nth-child(5) > td:nth-child(6)").text().replaceAll("\\s*", "");
        //政治面貌
        String occupation = user.selectFirst("#xjkpTable > tbody > tr:nth-child(6) > td:nth-child(4)").text().replaceAll("\\s*", "");
        student.setClasses(classes);
        student.setMajor(major);
        student.setCollege(college);
        student.setGrade(grade);
        student.setName(name);
        student.setMobile(mobile);
        student.setGender(sex.equals("男") ? "1" : "2");
        student.setOccupation(occupation);
        return student;
    }

    /**
     * 获取班级信息
     *
     * @return
     */
    public static String getClasses(String o) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(o);
        String trim = m.replaceAll("").trim();
        return StringUtils.hasText(trim) ? trim : "0";
    }

    public Map<String, Object> go(List<String> params, String cookie, boolean flag) throws SQLException {
        List<Student> students = new ArrayList<>();
        //获取用户姓名和学号
        Document user = Jsoup.parse(HttpClientConfig.doGet(cookie));
        String stuId = user.selectFirst("#account").val();
        String name = user.selectFirst("#realName").val();
        UserVO info = getInfo(cookie);
        return flag ? xuanxiu(params, cookie, students, stuId, name, info) : gpa(params, cookie, students, stuId, name, info);
    }

    private Map<String, Object> xuanxiu(List<String> params, String cookie, List<Student> students, String stuId, String name, UserVO info) {
        Document document = Jsoup.parse(HttpClientConfig.doPOST(params.get(0), cookie));
        Elements tr = document.getElementsByTag("tr");
        HashMap<String, Object> map = new HashMap<>();
        for (int i = 1; i < tr.size(); i++) {
            int c = i + 1;
            String subject = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(4)").html();
            String time = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(2)").html();
            String credit = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(7)").html();
            String grade100 = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(5)").text();
            String grade = Double.toString(Double.parseDouble(grade100) >= 60 ? ((Double.parseDouble(grade100) - 50) / 10.0) : 0);
            Student student = new Student(stuId, name, subject, credit, grade, time, grade100);
            student.setCla(info.getClasses());
            student.setMajor(info.getMajor());
            student.setClasses(info.getGrade());
            students.add(student);
        }
        map.put("students", students);
        return map;
    }

    private Map<String, Object> gpa(List<String> params, String cookie, List<Student> students, String stuId, String name, UserVO info) {
        HashMap<String, Object> map = new HashMap<>();
        for (String param : params) {
            Document document = Jsoup.parse(HttpClientConfig.doPOST(param, cookie));
            if (param.equals("kksj=")) {
                map.put("allCredit", document.text().split("所修总学分:")[1].split(" 平均学分绩点:")[0]);
            }
            Elements tr = document.getElementsByTag("tr");
            for (int i = 1; i < tr.size(); i++) {
                int c = i + 1;
                String isKaoshi = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(11)").html();
                String isBixiu = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(13)").html();
                String subject = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(4)").html();
                boolean isRe = false;
                for (Student student : students) {
                    if (student.getSubject().equals(subject)) {
                        String grade = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(9)").html();
                        String grade100 = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(5)").text();
                        student.setGrade(Double.parseDouble(grade) > Double.parseDouble(student.getGrade()) ? grade : student.getGrade());
                        student.setGrade_one(Double.parseDouble(grade100) > Double.parseDouble(student.getGrade_one()) ? grade100 : student.getGrade_one());
                        isRe = true;
                        break;
                    }
                }
                if (isRe) {
                    continue;
                }
                if (!subject.equals("计算机基础1") && !subject.contains("体育") && isKaoshi.equals("考试") && (isBixiu.equals("必修") || isBixiu.equals("限选")) && !subject.equals("大学物理实验")) {
                    String time = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(2)").html();
                    String credit = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(7)").html();
                    String grade100 = document.selectFirst("#dataList > tbody > tr:nth-child(" + c + ") > td:nth-child(5)").text();
                    String grade = Double.toString(Double.parseDouble(grade100) >= 60 ? ((Double.parseDouble(grade100) - 50) / 10.0) : 0);
                    Student student = new Student(stuId, name, subject, credit, grade, time, grade100);
                    student.setCla(info.getClasses());
                    student.setMajor(info.getMajor());
                    student.setClasses(info.getGrade());
                    students.add(student);
                }
            }
        }
        studentMapper.insertOrUpdateBatch(students);
        map.put("students", students);
        return map;
    }

}
